package cn.shop.cloud.service.impl;

import cn.shop.cloud.common.BusinessException;
import cn.shop.cloud.domain.User;
import cn.shop.cloud.mapper.UserMapper;
import cn.shop.cloud.redis.MemberServerKeyPrefix;
import cn.shop.cloud.redis.MyRedisTemplate;
import cn.shop.cloud.service.UserService;
import cn.shop.cloud.web.msg.MemberCodeMsg;
import cn.shop.cloud.web.util.MD5Util;
import cn.shop.cloud.web.vo.LoginVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @program: shop-parent
 * @ClassName UserServiceImpl
 * @description:
 * @author: Mokio
 * @create: 2024−12-24 11:38
 * @Version 2024 2.2 ; jdk1.8.0_181
 **/
@Service
public class UserServiceImpl implements UserService, InitializingBean {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Override
    public String login(LoginVo loginVo) {

        // 注意这里用到了jsr 303

        User user = this.find(Long.parseLong(loginVo.getUsername()));

        if(user == null){
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }
        // 判断密码前别忘了用盐加密

        String encodePwd = MD5Util.encode(loginVo.getPassword(),user.getSalt());

        // 判断密码是否一致，不一致直接报异常
        if(!user.getPassword().equals(encodePwd)){
            throw  new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }

        // 密码正确则生成token
        String token = createToken(user);


        return token;
    }


    // 生成token
    private String createToken(User user) {
        // 这里的逻辑是随机生成了一个uuid，然后将里边的横线去掉，得到一个32位的字符串
        String token = UUID.randomUUID().toString().replace("-", "");
        myRedisTemplate.set(MemberServerKeyPrefix.USER_TOKEN,token,user);
        //真正的key  reallyKey = MemberServerKeyPrefix.USER_TOKEN+token

        return token;
    }

    // 根据token获取用户信息
    @Override
    public User getUserByToken(String token) {
        // 从redis利用令牌中获取用户信息，将用户前缀和token作为key，返回用户对象
        return myRedisTemplate.get(MemberServerKeyPrefix.USER_TOKEN,token,User.class);
    }

    @Override
    public User find(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //会在所有的配置装载完毕后自动调用这个方法
        System.out.println("===============================>"+myRedisTemplate);

        /**
         * 我们班级解决 分布式session的方案是: redis + token
         */
    }

}
